package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.controller.vo.ResponseOrdersVo;
import com.example.controller.vo.Result;
import com.example.entity.Orders;
import com.example.entity.PageView;
import com.example.entity.Product;
import com.example.entity.User;
import com.example.service.IOrdersService;
import com.example.service.IProductService;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单信息表 前端控制器
 * </p>
 *
 * @author yzy
 * @since 2025-08-04
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private IOrdersService orderService;

    @Autowired
    private IOrdersService ordersService;


    @Autowired
    private IUserService iuserService;

    @Autowired
    private IProductService iproductService;


    @GetMapping("/list")
    public Result getOrderList(@RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                               @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "code", required = false) String code,
                               @RequestParam(value = "tradeStatus", required = false) Boolean tradeStatus) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(code)) {
            queryWrapper.like("code", code);
        }
        if (tradeStatus != null) {
            queryWrapper.eq("trade_status", tradeStatus);
        }
        Page<Orders> page = this.ordersService.page(new Page<>(pageNum, pageSize), queryWrapper);
        PageView pageView = new PageView();
        pageView.setPageNum(Integer.parseInt(page.getCurrent() + ""));
        pageView.setPageSize(Integer.parseInt(page.getSize() + ""));
        pageView.setAllRow(page.getTotal());
        pageView.setTotalPage(page.getPages());
        pageView.setData(page.getRecords());
        return Result.success(pageView);
    }

    //查看订单详情，按id查询
    @GetMapping("/{id}")
    public Result getOrderById(@PathVariable("id") Integer id) {
        Orders orders = ordersService.getById(id);
        return Result.success(orders);
    }

    //删除订单
    @DeleteMapping("/{id}")
    public Result deleteOrderById(@PathVariable("id") Integer id) {
        ordersService.removeById(id);
        return Result.success(null);
    }

    @GetMapping("/userlist")
    public Result getuserOrderList(@RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize,

                                   @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                   @RequestParam(value = "userName",required = false) String userName
    ) {
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_account",userName);
        User user = iuserService.getOne(queryWrapper1);
        Integer userId=user.getId();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        if(userId!=null){
            queryWrapper.like("user_id",userId);
        }
        Page<Orders> page = this.ordersService.page(new Page<>(pageNum,pageSize),queryWrapper);
        List<Orders> ordersList = page.getRecords();
        List<ResponseOrdersVo> voList = new ArrayList<>();
        for (Orders order : ordersList) {
            // 创建VO对象并复制基本字段
            ResponseOrdersVo vo = new ResponseOrdersVo();
            vo.setId(order.getId());
            vo.setCode(order.getCode());
            vo.setDetail(order.getDetail());
            vo.setUserId(order.getUserId());
            vo.setProductId(order.getProductId());
            vo.setBuyPrice(order.getBuyPrice());
            vo.setTradeStatus(order.getTradeStatus());
            vo.setTradeTime(order.getTradeTime());
            vo.setCreateTime(order.getCreateTime());
            // 补充VO特有的关联字段（需要查询数据库获取）
            // 1. 获取商品名称和封面

            Product product = iproductService.getById(order.getProductId());

            if (product != null) {
                vo.setProductName(product.getName());
                vo.setCoverList(product.getCoverList());
                vo.setUserId(product.getUserId());// 假设Product有coverList字段
            }
            // 2. 获取用户名
            User user1 = iuserService.getById(vo.getUserId());
            if (user1 != null) {
                vo.setUserName(user1.getUserName()); // 假设User有userName字段
            }
            // 添加到VO列表
            voList.add(vo);
        }
        Page<ResponseOrdersVo> voPage = new Page<>(pageNum, pageSize);
        voPage.setRecords(voList);
        PageView pageView = new PageView();
        pageView.setPageNum(Integer.parseInt(voPage.getCurrent()+""));
        pageView.setPageSize(Integer.parseInt(voPage.getSize()+""));
        pageView.setAllRow(page.getTotal());
        pageView.setTotalPage(page.getPages());
        pageView.setData(voPage.getRecords());
        return Result.success(pageView);
    }


    /**添加订单*/
    @PostMapping("/add")
    public Result add(@RequestParam(value = "productId",required = false) Integer productId,
                      @RequestParam(value = "userName",required = false) String userName
    ){
        //获取当前用户Id
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_account",userName);
        User user = iuserService.getOne(queryWrapper1);
        if (user!=null&&!"".equals(user)){
        Integer userId=user.getId();
        orderService.addorder(productId,userId);
        return Result.success("成功添加订单");}
        return Result.failed("不存在该用户");
    }
    /**完成订单*/
    @PostMapping("/complete")
    public Result completeOrder(@RequestParam(value = "detail",required = false) String detail,
                                @RequestParam(value = "code",required = false) String code
    ){
        QueryWrapper<Orders> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("code",code);
        Orders orders = ordersService.getOne(queryWrapper);
        orders.setDetail(detail);
        ordersService.completeOrder(orders);
        return Result.success("订单完成");
    }

}
